package com.foreveross.proxyip.core.pools.thread;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.dayatang.domain.InstanceFactory;
import com.foreveross.proxyip.core.BaseCode;
import com.foreveross.proxyip.core.pools.AvailablePool;
import com.foreveross.proxyip.core.pools.PoolsManager;
import com.foreveross.proxyip.infra.base.ddd.repository.IBaseRepository;

/**
 * 该类setConfig方法实例化后，必须调用 该线程Config类配置间隔时间，不断开启 N个 检入|检出 线程处理规定集合
 * 
 * @author lyq
 * 
 */
@SuppressWarnings("rawtypes")
public abstract class CircleThread implements Runnable {
	protected final Logger log = LoggerFactory.getLogger(this.getClass());
	protected AvailablePool pool = null;
	IBaseRepository repository = null;// 提供jpa数据库操作的支持
	public Integer threadTimeout = null;

	// public long preValidate = 0;//上次
	Class clzz = null;
	/*** 第一次执行是否初始化，默认 false ***/
	protected boolean isInit = true;
	/**** config配置数据 ****/
	protected int separationTime;
	
	private CheckType currType;
	
	protected enum CheckType {
		CHECKIN, CHECKOUT;
		
		public void sleep(AvailablePool pool) throws InterruptedException {
			long sleepTime = 0;
			
			if (this == CHECKIN) {
				sleepTime = pool.checkInInterval;
			} else {
				sleepTime = pool.checkOutInterval;
			}
			
			TimeUnit.MILLISECONDS.sleep(sleepTime);
		}
	}

	public CircleThread(AvailablePool pool, CheckType type) throws Exception {
		this.repository = InstanceFactory.getInstance(IBaseRepository.class, "channelEntityRepository");
		threadTimeout = Integer.parseInt(BaseCode .getValue("THREAD_EXECUTE_TIMEOUT"));
		this.pool = pool;
		currType = type;
	}

	public void run() {
		while (!Thread.currentThread().isInterrupted()) {
			try {
				// log.info("name:"+pool.getPoolName()+"====="+clzz.getSimpleName()+" ======pool.size():"+pool.size()+"=======");
				/*if (!this.isInit || needSleep()) {
					this.sleep();
				}*/
				
				if (pool == null || !pool.openStatus) {// 池关闭
					break;
				}
				
				publishTask();
				currType.sleep(pool);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					//executeFinish();
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}
	}

	public abstract boolean needSleep() throws Exception;

	/**
	 * 最后执行
	 * 
	 * @throws Exception
	 */
	protected abstract void executeFinish() throws Exception;

	/**
	 * 设置初始化是否沉睡
	 */
	public void setIsInit(boolean bool) {
		this.isInit = bool;
	}

	public abstract void publishTask() throws Exception;

	// public abstract boolean isExecute();

	protected void sleep() throws InterruptedException {
		// log.info(pool.getPoolName()+getName()+"线程沉睡"+separationTime/1000+"秒");
		Thread.sleep(separationTime);
	}

	/**
	 * 返回检入或者检出的名称
	 */
	public abstract String getName();

}
